package com.dgut.controller;


import com.dgut.bean.User;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.dgut.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;

import java.util.UUID;

@Controller


@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @RequestMapping("/")
    public String main() {
        return "main";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public ModelAndView login(String name, String password, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.findUserByUsername(name);
        //登录成功进入主页，登录失败重新进入登录页
        //判断用户名是否存在
        if (user == null) {
            modelAndView.addObject("msg1", "用户名不存在");
            modelAndView.setViewName("login");
        } else {
            //判断密码是否正确
            if (password.equals(user.getPassword())) {
                //登录成功，user加入session
                request.getSession().setAttribute("user", user);
                modelAndView.addObject("user", user);
                modelAndView.setViewName("main");
            } else {
                //登录失败返回登录页面
                modelAndView.addObject("msg1", "密码错误");
                modelAndView.setViewName("login");
            }
        }


        return modelAndView;
    }

    @GetMapping("/signup")
    public String register() {
        return "signup";
    }


    @PostMapping("/signup")
    public ModelAndView register(String username, String password, String confirmPassword) {
        ModelAndView modelAndView = new ModelAndView();
//        判断用户名和密码是否为空。
        if (username == "" || password == "" || confirmPassword == "") {
            modelAndView.addObject("msg2", "用户名或密码为空");
            modelAndView.setViewName("signup");
        } else {
//            判断username同名。
            User user = userService.findUserByUsername(username);
            if (user != null) {
                modelAndView.addObject("msg2", "用户名已注册");
                modelAndView.setViewName("signup");
            } else {
//                判断两次密码是否一致。
                if (!password.equals(confirmPassword)) {
                    modelAndView.addObject("msg2", "两次密码输入不一致");
                    modelAndView.setViewName("signup");
                } else {
//                    注册成功，返回登录页
                    userService.addUser(username, password);
                    User addUser = userService.findUserByUsername(username);
                    System.out.println(addUser);
                    modelAndView.addObject("user", addUser);
                    modelAndView.setViewName("login");
                }
            }
        }
        return modelAndView;
    }

    //    注销user
    @RequestMapping("/logoutUser")
    public String logoutUser(HttpSession session) {
        session.removeAttribute("user");
        return "login";
    }


    //    查看个人信息
    @RequestMapping("/personalInformationJson")
    public @ResponseBody
    User personalInformationJson(HttpServletRequest request) {
        User sessionUser = (User) request.getSession().getAttribute("user");
        User user = userService.findUserById(sessionUser.getUid());
        return user;
    }

    @RequestMapping("/personalInformation")
    public String personalInformation() {
        return "personInformation";
    }

    //修改个人信息
    @PostMapping("/updatePersonalInformation")
    public void updatePersonalInformation(@RequestBody User actionUser, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        User user = (User) request.getSession().getAttribute("user");
//        即使上传的数据没有username和password，似乎会通过session获取得到，因为属性同名。
        System.out.println(actionUser);
//        数据库更新数据
        userService.updateUserInformation(actionUser);
    }


    //处理上传头像
    @PostMapping("/upload")
    public String upload(MultipartFile imgFile, HttpServletRequest request) throws IOException {
//        1.图片保存到在指定目录
//        2.自己搭建的文件服务器（资源服务器）存储我们的图片，视频
//        3.现成的文件服务器
        //获取原始文件的文件名
        String originalFilename = imgFile.getOriginalFilename();
//        System.out.println("originalFilename :"+originalFilename);
//        获取后缀
        String extentName = originalFilename.substring(originalFilename.lastIndexOf("."));

        String uploadPath = request.getServletContext().getRealPath("/userImages");
//        System.out.println(uploadPath);

//       把⽂件加上随机数，防⽌⽂件重复
        String fileName = UUID.randomUUID().toString() + extentName;

        //保存文件
        imgFile.transferTo(new File(uploadPath, fileName));

//        获取未修改前的实体属性里的头像文件名。
        User user = (User) request.getSession().getAttribute("user");
//        修改实体属性里的头像文件名。

        userService.updateUserImage(user.getUid(), fileName);
//        根据路径删除之前的图片,因为每次clean时，target上传到的图片会被清理，就不实现了。

//        返回不了页面
        return "main";
    }




}
